package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Querys;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private AttrService attrService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Querys<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVO saveVO) {
        //1.保存SPU基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(saveVO,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> descList  = saveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",descList));
        spuInfoDescService.saveSpuDesc(spuInfoDescEntity);
        //3.保存spu图片集合 pms_spu_images
        List<String> images = saveVO.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = saveVO.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)){
            List<ProductAttrValueEntity> attrValueEntityList = baseAttrs.stream().map((attr) -> {
                ProductAttrValueEntity attrValue = new ProductAttrValueEntity();
                attrValue.setAttrId(attr.getAttrId());
                AttrEntity byId = attrService.getById(attr.getAttrId());
                attrValue.setAttrName(byId.getAttrName());
                attrValue.setAttrValue(attr.getAttrValues());
                attrValue.setQuickShow(attr.getShowDesc());
                attrValue.setSpuId(spuInfoEntity.getId());
                return attrValue;
            }).collect(Collectors.toList());
            productAttrValueService.saveProductAttr(attrValueEntityList);
        }
        //5.保存spu的积分信息 sms_spu_bounds
        Bounds bounds = saveVO.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R resp = couponFeignService.saveSpuBounds(spuBoundTo);
        if (resp.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }
        //6.保存当前spu对应的所有sku信息 pms_sku_info
        List<Skus> skus = saveVO.getSkus();
        if (skus != null && skus.size() > 0){
            skus.forEach((item) ->{
                SkuInfoEntity skuInfo = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfo);
                skuInfo.setBrandId(spuInfoEntity.getBrandId());
                skuInfo.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfo.setSpuId(spuInfoEntity.getId());
                skuInfo.setSaleCount(0L);
                //设置默认图片
                List<Images> imgList = item.getImages();
                for (Images img : imgList) {
                    if (img.getDefaultImg() == 1){
                        skuInfo.setSkuDefaultImg(img.getImgUrl());
                        break;
                    }
                }
                skuInfoService.saveSkuInfo(skuInfo);
                List<SkuImagesEntity> imagesList = imgList.stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfo.getSkuId());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    return !StringUtils.isEmpty(entity);
                }).collect(Collectors.toList());
                //保存sku的图片属性
                skuImagesService.saveBatch(imagesList);
                //保存sku的销售属性
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleList = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSale = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSale);
                    skuSale.setSkuId(spuInfoEntity.getId());
                    return skuSale;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleList);
                //sku的优惠信息、满减信息 gulimall-sms sms_sku_ladder\sms_sku_full
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuInfo.getSkuId());
                // 有满减信息才会去调用服务
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) > 0){
                    R res = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (res.getCode() != 0){
                        log.error("远程保存sku信息失败-----");
                    }
                }
            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((w) -> {
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brnad_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Querys<SpuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }
}